package org.crag.cafca.gui.servlet;

import java.io.IOException;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.crag.cafca.gui.MenuManager;
import org.crag.cafca.gui.Submenu;
import org.crag.cafca.util.Constants;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Servlet implementation class Tree
 */
@WebServlet("/TreeServlet")
public class TreeServlet extends HttpServlet 
{
	/**
	 * The log4J logger. See http://logging.apache.org/log4j/1.2/index.html for more info.
	 */
	private static Logger log=Logger.getLogger(new Throwable().getStackTrace()[0].getClassName());

	private static final long serialVersionUID = 1L;

	private MenuManager menuManager;

    /**
     * Default constructor. 
     */
    public TreeServlet() 
    {
    	
    }

    @Override
    public void init() throws ServletException 
    {
    	super.init();
		this.menuManager=MenuManager.getMenuManager();
		if (menuManager==null)
		{
			log.error("Impossible to get the MenuManager in TreeServlet");
			return;
		}
    }
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
		JSONObject resultJson;
		String mode=request.getParameter(Constants.HTTP_MODE);
		String node=request.getParameter(Constants.HTTP_NODE);
		String hash=request.getParameter(Constants.HTTP_HASH);

		log.info("TreeServlet called with the parameters : mode="+mode+", node="+node+", hash="+hash);
		
		try
		{
			resultJson=new JSONObject();
						
			if (mode==null)
			{
				log.warn("TreeServlet requests a mode");
				resultJson.put(Constants.JSON_RESULT, "TreeServlet requests a mode");
				sendResponse(response,resultJson,false);
				return;
			}

			if (mode.equals("getChildren"))
			{
				Vector<Submenu> requestedSubmenus=new Vector<Submenu>();
				if (node==null)
				{
					log.warn("TreeServlet.getChildren called and node is not specified");
					resultJson.put(Constants.JSON_RESULT, "TreeServlet.getChildren called and node is not specified");
					sendResponse(response,resultJson,false);
					return;					
				}
				

				Submenu parent=menuManager.getMenu().findSubmenu(node);
				if (parent!=null)
				{
					requestedSubmenus.addAll(parent.getSubmenus());										
				}
							
				sendSubmenus(response,resultJson,requestedSubmenus);
			}
			else
			{
				resultJson.put(Constants.JSON_RESULT, "TreeServlet: Unknown mode.");
				sendResponse(response,resultJson,false);
			}
		}
		catch (JSONException e)
		{
			log.error("Error during the creation of the JSON string :"+e.getMessage());
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}    
	}
    
	private void sendSubmenus(HttpServletResponse response,JSONObject resultJson,Vector<Submenu> submenus) throws JSONException, IOException
	{
		JSONArray childrenJSON=new JSONArray();
		for (Submenu submenu:submenus)
		{ 
			childrenJSON.put(convertSubmenuToJSON(submenu));
		}
			
		resultJson.put(Constants.JSON_RESULT, childrenJSON);
		sendResponse(response,resultJson,true);
	}
    
	private JSONObject convertSubmenuToJSON(Submenu submenu) throws JSONException
	{
		JSONObject result=new JSONObject();
		result.put(Constants.JSON_ID, submenu.getFullId());
		result.put(Constants.JSON_TEXT, submenu.getName());
		result.put(Constants.JSON_URL, submenu.getUrl());		
		result.put(Constants.JSON_LEAF, submenu.isLeaf());		
		
		return result;
	}
	
	private void sendResponse(HttpServletResponse response,JSONObject resultJson,boolean success) throws IOException, JSONException 
	{
		resultJson.put(Constants.JSON_SUCCESS, success);
		response.getWriter().write(resultJson.toString());
		response.setStatus(HttpServletResponse.SC_OK);
	}
}
